package com.bosssoft.boss_exam_web.Controller;


import com.bosssoft.boss_exam_core.enums.ResultCode;
import com.bosssoft.boss_exam_core.exception.*;
import com.bosssoft.boss_exam_core.util.web.ResponseUtil;
import com.bosssoft.boss_exam_core.validator.Order;
import com.bosssoft.boss_exam_core.validator.Sort;
import com.bosssoft.boss_exam_db.entity.Company;
import com.bosssoft.boss_exam_db.entity.Subject;
import com.bosssoft.boss_exam_db.service.busines.AdminService;
import com.bosssoft.boss_exam_db.service.busines.SubjectService;
import com.bosssoft.boss_exam_web.common.annotation.LoginAdmin;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/subject")
@Validated
@Slf4j
@Api(value="科目控制器")
public class SubjectController {

    //注入科目服务
    @Autowired
    private SubjectService subjectService;

    //注入管理员服务
    @Autowired
    private AdminService adminService;

    @ApiOperation(value="科目查询", notes="可根据科目名称查询科目" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="name", value="科目名称", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="page", value="当前页码", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="limit", value="每页显示条数", dataType = "String", required=false, dataTypeClass=Integer.class),
            @ApiImplicitParam(name="sort", value="排序依据", dataType = "String", required=false, dataTypeClass=String.class),
            @ApiImplicitParam(name="order", value="排序方式", dataType = "String", required=false, dataTypeClass=String.class)
    })
    @GetMapping("/list")
    public Object list(@LoginAdmin String adminId,
                       @RequestParam String name,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        if ( adminId == null) {
            return ResponseUtil.unlogin();
        }
        //查询当前用户所在公司
        Company company=adminService.selectAdminBelongCompany(adminId);
        if(company==null){
            log.error("【严重警告】该管理员没有公司");
            throw new BusinessException("该管理员，没有归属公司");
        }
        PageInfo<Subject> subjectPageInfo = subjectService.queryByCondition(company,name,page, limit, sort, order);
        if(subjectPageInfo==null){
            log.error("【业余错误】，查询pageInfo为空");
            throw new QueryDataException();
        }else {
            Map<String, Object> data = new HashMap<>();
            data.put("total", subjectPageInfo.getTotal());
            data.put("items", subjectPageInfo.getList());
            return ResponseUtil.ok(data);
        }
    }

    @ApiOperation(value="科目添加", notes="添加科目" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="subject", value="科目对象json", dataType = "Subject", required=true, dataTypeClass= Subject.class),
    })
    @PostMapping("/create")
    public Object create(@LoginAdmin String adminId, @RequestBody Subject subject) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Company company=adminService.selectAdminBelongCompany(adminId);
        if(company==null){
            log.error("【严重警告】该管理员没有公司");
            throw new BusinessException("该管理员，没有归属公司");
        }
        subject.setCompanyId(company.getId());
        int recordNum = subjectService.saveNotNull(subject);
        if(recordNum==1){
            return ResponseUtil.ok(subject);
        }else{
            log.error("【系统错误】 保存科目失败");
            throw  new UpdateEntityException();
        }
    }

    @ApiOperation(value="科目详细信息查询", notes="可根据科目的ID查询详情" ,httpMethod="GET",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="科目ID，非空", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @GetMapping("/read")
    public Object read(@LoginAdmin String  adminId, @NotNull Integer id) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Subject subject = null;
        try {
            subject = subjectService.selectByKey(id);
        }  catch (NoSuchMethodException | InvocationTargetException |IllegalAccessException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }catch (Exception e){
            log.error("【业务错误】 读取实体异常"+e);
            throw  new QueryDataException();
        }
        return ResponseUtil.ok(subject);
    }


    @ApiOperation(value="科目更新", notes="更新科目" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="subject", value="科目对象json，必须携带科目ID", dataType = "Subject", required=true, dataTypeClass= Subject.class),
    })
    @PostMapping("/update")
    public Object update(@LoginAdmin String  adminId, @RequestBody Subject subject) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        int recordNum = subjectService.updateNotNull(subject);
        if(recordNum==1){
            return ResponseUtil.ok(subject);
        }else{
            log.error("【系统错误】 保存科目失败");
            throw  new UpdateEntityException();
        }
    }

    @ApiOperation(value="科目删除", notes="可根据科目的ID逻辑删除科目" ,httpMethod="POST",response = Object.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="科目ID，非空", dataType = "String", required=true, dataTypeClass=String.class),
    })
    @PostMapping("/delete")
    public Object delete(@LoginAdmin String adminId, @RequestParam String id) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        Subject subject = new Subject();
        subject.setId(id);
        try {
            int i = subjectService.deleteForLogic(subject);
        } catch (NoSuchMethodException|IllegalAccessException|InvocationTargetException e) {
            log.error("【系统错误】 反射操作异常"+e);
            throw  new ReflectionException(ResultCode.SYSTEM_INNER_ERROR);
        }catch (Exception e) {
            log.info("【业务错误】 逻辑删除科目异常"+e);
            throw  new DeleteEntityException();
        }
        return ResponseUtil.ok();
    }

    @ApiOperation(value="查询公司的科目", notes="查询当前操作用户所处公司的所有开设科目" ,httpMethod="GET",response = Object.class)
    @GetMapping("/subjects")
    public Object getSubjects(@LoginAdmin String adminId) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        //查询当前用户所在公司
        Company company=adminService.selectAdminBelongCompany(adminId);
        List<Subject> subjects= subjectService.queryByCompanyId(company.getId());
        return ResponseUtil.ok(subjects);
    }
}
